"use strict";
//前后端HTTP协议交互
//因为request 回调函数参数[err, res, body]问题无法直接转换成Promise模式
const mvc = require('cosjs.mvc');
const request = mvc.library.require('request');
//向游戏服发送数据
exports.select = function (ts, sid, avg) {
    // console.log("select  0 db:",sid,avg)
    return Promise.resolve().then(() => {
        let b = mvc.config.get("branch.id");
        let p = mvc.config.get("local.port") || 8080;
        let r = mvc.config.get("spirit.route") || 'spirit';

        let arr = mvc.config.get("sid");
        let api = ['', 's' + arr[0], r, 'select'].join('/');
        let uri = ['http://127.0.0.1', p].join(':')
        let url = [uri, api].join('');
        let data = { "ts": ts, "sid": sid || 0, "avg": avg || 0, "branch": b };

        // console.log("select  1 db:",url,data)
        // console.log("select  1 db  ret %v:",request.post(url,data,true))
        return request.post(url, data, true);
    }).then(ret => {
        // console.log("select  2 db:",sid,avg)
        // console.log("select  2 db ret:",ret)
        return mvc.library("promise/callback", ret)
    });
}

exports.gzone = function (api, data) {
    return exports.select(9).then(ret => {
        if (!ret) {
            // var stack = new Error().stack
            // console.log("api-----1  ", stack )
            // console.log("api-----1.1  ",api,ret);
            // console.log("api-----1.2  %v",ret);
            // console.log("api-----1.3  %v", mvc.config.get("branch"));
            return Promise.reject("server empty")
        }
        let branch = mvc.config.get("branch");
        let url = `http://${ret['ip']}:${ret['local']}/${branch.id}${api}`;
        mvc.library("sign/create", data, branch.secret);
        return request.post(url, data, true).then(ret => mvc.library('promise/callback', ret))
    })
}

exports.game = function (sid, api, data) {
    return exports.select(1, sid).then(ret => {
        if (!ret) {
            // console.log("api-----  sid  2  ",sid,api);
            return Promise.reject("server empty")
        }
        let branch = mvc.config.get("branch");
        let url = `http://${ret['ip']}:${ret['local']}/s${sid}${api}`;
        mvc.library("sign/create", data, branch.secret);
        return request.post(url, data, true).then(ret => mvc.library('promise/callback', ret))
    })
}

exports.battle = function (sid, api, data) {
    return exports.select(3, sid).then(ret => {
        if (!ret) {
            // console.log("api-----  sid  3  ",sid,api);
            return Promise.reject("server empty")
        }
        let branch = mvc.config.get("branch");
        let url = `http://${ret['ip']}:${ret['local']}${api}`;
        mvc.library("sign/create", data, branch.secret);
        return request.post(url, data, true).then(ret => mvc.library('promise/callback', ret))
    })
}

